package com.zheng.oss.web.service;

import com.alibaba.fastjson.JSONObject;
import com.zheng.common.util.PropertiesFileUtil;
import com.zheng.oss.common.constant.OssConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by ZhangShuzheng on 2017/5/15.
 */
@Service
public class QiniuOssService {

	private static Logger _log = LoggerFactory.getLogger(QiniuOssService.class);

	/**
	 * 签名生成
	 * @return
	 */
	public JSONObject policy() {
		JSONObject result = new JSONObject();
		// 存储目录
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String dir = sdf.format(new Date());

		// 提交节点
		String action = "http://" +  OssConstant.OSS_ENDPOINT;
		StringMap putPolicy = new StringMap();
		putPolicy.put("callbackUrl", OssConstant.OSS_CALLBACK);
		putPolicy.put("callbackBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"fsize\":$(fsize)}");
		putPolicy.put("callbackBodyType", "application/json");

		try {
			Auth auth = Auth.create(PropertiesFileUtil.getInstance("config").get("oss.accessKeyId"), PropertiesFileUtil.getInstance("config").get("oss.accessKeySecret"));
			long expireSeconds = OssConstant.OSS_EXPIRE;
			String upToken = auth.uploadToken(OssConstant.OSS_BUCKET_NAME, null, expireSeconds, putPolicy);

			// 返回结果
			result.put("upToken", upToken);
			result.put("dir", dir);
			result.put("action", action);
		} catch (Exception e) {
			_log.error("签名生成失败", e);
		}
		return result;
	}

	/**
	 * 验证callback合法性
	 * @param callbackAuthHeader
	 * @param callbackBody
	 * @return
	 */
	public boolean isValidCallback(String callbackAuthHeader,byte[] callbackBody) {
		Auth auth = Auth.create(PropertiesFileUtil.getInstance("config").get("oss.accessKeyId"), PropertiesFileUtil.getInstance("config").get("oss.accessKeySecret"));
		//定义回调内容的组织格式
		String callbackBodyType = "application/json";
		//检查是否为七牛合法的回调请求
		boolean validCallback = auth.isValidCallback(callbackAuthHeader, OssConstant.OSS_CALLBACK, callbackBody, callbackBodyType);
		if (validCallback) {
			return true;
		} else {
			//这是哪里的请求，被劫持，篡改了吧？
			return false;
		}
	}
}
